package com.yxhl.zoume.core.func.map.ui.fragment;


import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.yxhl.protobuf.StationEntry;
import com.yxhl.zoume.R;
import com.yxhl.zoume.core.func.map.overlay.DrivingRouteOverlay;
import com.yxhl.zoume.core.func.map.ui.event.SelectUpPointEvent;
import com.yxhl.zoume.core.tripsmgmt.ui.CustomDrivingRouteOverlay;
import com.yxhl.zoume.core.tripsmgmt.ui.activity.BusMapContainerActivity;
import com.yxhl.zoume.data.rxbus.RxBus;
import com.yxhl.zoume.utils.ZMMapUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * created by sugarya
 * 定制巴士地图 选择乘车站点
 */
public class ZouMeBusUpPointFragment extends BaseMapFragment implements RouteSearch.OnRouteSearchListener, AMap.OnMarkerClickListener {
    public static final int SUCCESS = 1000;
    private static final String TAG = "CustomBusStationSelectFrag";
    private static final String INTENT_KEY_ZOUME_BUS_MAP_UPPOINTS = "intent_key_zoume_bus_map_uppoints";
    private static final float MAP_ZOOM_LEVEL = 13f;

    /**
     * 地图视野移动的延迟时间(毫秒)
     */
    private static final int LOCATION_ZOOM_MOVE_DELAY = 1500;


    //widgets
    @BindView(R.id.frame_custom_bus_station_location)
    FrameLayout stationLocationFrame;

    //arguments
    private RouteSearch mRouteSearch;


    /**
     * 途径点集合
     */
    private List<StationEntry> mAllStations = new ArrayList<>();
    private List<LatLonPoint> mAllUpPoints = new ArrayList<>();
    private ArrayList<MarkerOptions> mArrivalMarkerOptionList = new ArrayList<>();
    private ArrayList<Marker> mAllMarkers = new ArrayList<>();
    private DrivingRouteOverlay mDrivingRouteOverlay;

    public ZouMeBusUpPointFragment() {
        // Required empty public constructor
    }

    public static ZouMeBusUpPointFragment newInstance(List<StationEntry> upPoints) {

        Bundle args = new Bundle();
        args.putSerializable(INTENT_KEY_ZOUME_BUS_MAP_UPPOINTS, (Serializable) upPoints);
        ZouMeBusUpPointFragment fragment = new ZouMeBusUpPointFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleArgument();
    }

    private void handleArgument() {
        Bundle args = getArguments();
        if (null != args) {
            mAllStations = (List<StationEntry>) args.getSerializable(INTENT_KEY_ZOUME_BUS_MAP_UPPOINTS);
            convertStationsToLatLonPoints(mAllStations);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);

        setArrivalPoints();
        startDrivingRouteSearch();

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @OnClick(R.id.frame_custom_bus_station_location)
    public void onStationLocationClick(View view) {
        Location location = mMapView.getMap().getMyLocation();
        if (location != null) {
            animateMoveTo(new LatLng(location.getLatitude(), location.getLongitude()), getLocationMapZoomLevel());
        }
    }


    /**
     * List<StationEntry> 转换成 List<LatLonPoint>
     *
     * @param stations
     * @return
     */
    private void convertStationsToLatLonPoints(List<StationEntry> stations) {
        for (StationEntry s : stations) {
            mAllUpPoints.add(new LatLonPoint(Double.valueOf(s.getLatitude()), Double.valueOf(s.getLongitude())));
        }
    }

    private void startDrivingRouteSearch() {
        mRouteSearch = new RouteSearch(mActivity);
        mRouteSearch.setRouteSearchListener(this);

        RouteSearch.DriveRouteQuery driveRouteQuery = new RouteSearch.DriveRouteQuery(
                new RouteSearch.FromAndTo(
                        mAllUpPoints.get(0),
                        mAllUpPoints.get(mAllUpPoints.size() - 1)),
                RouteSearch.DrivingDefault,
                mAllUpPoints,
                null,
                "");
        mRouteSearch.calculateDriveRouteAsyn(driveRouteQuery);
    }


    /**
     * 设置所有途径站点
     */
    private void setArrivalPoints() {
        mArrivalMarkerOptionList.clear();
        int size = mAllUpPoints.size();
        for (int i = 0; i < size; i++) {
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions
                    .anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_meiyoujinguozhandian))
                    .position(ZMMapUtils.convertToLatLng(mAllUpPoints.get(i)));
            mArrivalMarkerOptionList.add(markerOptions);
        }
        mAllMarkers = mMapView.getMap().addMarkers(mArrivalMarkerOptionList, true);

        mMapView.getMap().setOnMarkerClickListener(this);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        int selectIndex = mAllMarkers.indexOf(marker);
        final StationEntry station = mAllStations.get(selectIndex);

        MaterialDialog.Builder builder = new MaterialDialog.Builder(getContext())
                .content("确定在 " + station.getStationName() + " 上车?")
                .positiveText(R.string.dialog_confirm)
                .negativeText(R.string.dialog_cancel)
                .positiveColorRes(R.color.app_primary_blue)
                .canceledOnTouchOutside(false);
        MaterialDialog dialog = builder.build();
        dialog.show();

        builder.onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                RxBus.getInstance().send(new SelectUpPointEvent(station));
                getActivity().finish();
            }
        });

        return false;
    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int code) {
        if (code == SUCCESS) {
            if (driveRouteResult != null) {
                List<DrivePath> drivePathList = driveRouteResult.getPaths();
                if (drivePathList != null && drivePathList.size() > 0) {
                    DrivePath drivePath = drivePathList.get(0);
                    mDrivingRouteOverlay = new CustomDrivingRouteOverlay(
                            mActivity,
                            mMapView.getMap(),
                            drivePath,
                            driveRouteResult.getStartPos(),
                            driveRouteResult.getTargetPos(),
                            mAllUpPoints.get(0),
                            mAllUpPoints.get(mAllUpPoints.size() - 1)
                    );
                    mDrivingRouteOverlay.setThroughPointIconVisibility(false);
                    mDrivingRouteOverlay.setNodeIconVisibility(false);
                    mDrivingRouteOverlay.addToMap();
                    mDrivingRouteOverlay.zoomToSpan();

                    //移动到定位处的标示
                    mBaseStartMoveToLocation = true;
                }
            }
        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
    }


    @Override
    protected Marker getLocationMarker(AMap aMap, LatLng latLng) {
//        Location location = mMapView.getMap().getMyLocation();
//
//        MarkerOptions locationMarkerOptions = new MarkerOptions();
//        locationMarkerOptions
//                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_wo))
//                .position(new LatLng(location.getLatitude(),location.getLongitude()));

        return null;
    }

    @Override
    protected boolean setUpLocationStyle(AMap aMap) {
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_wo));
        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
        myLocationStyle.strokeColor(Color.TRANSPARENT);
        aMap.setMyLocationStyle(myLocationStyle);

        aMap.getUiSettings().setZoomControlsEnabled(true);

        return true;
    }

    @Override
    protected float getLocationMapZoomLevel() {
        return MAP_ZOOM_LEVEL;
    }

    @Override
    protected void secondAnimateMove() {
        stationLocationFrame.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mDrivingRouteOverlay != null) {
                    mDrivingRouteOverlay.zoomToSpan();
                }
            }
        }, LOCATION_ZOOM_MOVE_DELAY);
    }

    @Override
    protected void initializeInjector() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_custom_bus_station_select;
    }

    @Override
    protected void setupToolBar() {
        ((BusMapContainerActivity) mActivity)
                .setToolbarTitle(getString(R.string.custom_bus_station_select_tool_bar_title));
    }
}
